package org.demo.xslt;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.InputSource;

/**
 * 
 * @author  
 * @date    2011-1-20
 * @file    org.demo.xml.XSLTUtil.java
 */
public class XSLTUtil {

	/**
	 * 测试
	 * @param args
	 * @throws IOException 
	 * @throws TransformerException 
	 */
	public static void main(String[] args) throws Exception {
		
		String xsl = XSLTUtil.class.getResource("data/transform-fn.xsl").getPath();
		String xml = XSLTUtil.class.getResource("data/customer.xml").getPath();
		InputStream in = new FileInputStream(xsl);
		// 构建输入输出流
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		Source from = new StreamSource(new File(xml));
		Result to = new StreamResult(out);
		// 构建转换器并执行转换
		Transformer transformer = getTransformer(in);
		transformer.transform(from, to);
		// 输出转换后结果
		String result = out.toString();
		System.out.println(result);
	}
	/**
	 * 创建并返回 transformer
	 * @param in_xsl
	 * @return a Transformer instance or null.
	 */
	public static Transformer getTransformer(InputStream in_xsl){
		Transformer transformer = null;
		try {
			SAXSource xsl = new SAXSource(new InputSource(in_xsl));
			transformer = TransformerFactory.newInstance()
			                                .newTransformer(xsl);			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return transformer;
	}

}
